package at.fhj.itm11.forum.beans;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.enterprise.context.RequestScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.inject.Inject;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import at.fhj.itm11.forum.data.PostRepository;
import at.fhj.itm11.forum.model.Post;

@ManagedBean
@RequestScoped
public class MediaBean {
	@Inject
	private PostRepository postRepository;
	
	public StreamedContent getImage() throws IOException {
		FacesContext context = FacesContext.getCurrentInstance();

		if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
			return new DefaultStreamedContent();
		} else {
			String id = context.getExternalContext().getRequestParameterMap()
					.get("id");
			Post post = postRepository.findById(Long.parseLong(id));
			if (post.getImage() != null) {
				return new DefaultStreamedContent(new ByteArrayInputStream(
						post.getImage()));

			} else {
				return new DefaultStreamedContent();
			}
		}
	}
	
	public StreamedContent getVideo() throws IOException {
		FacesContext context = FacesContext.getCurrentInstance();

		if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
			return new DefaultStreamedContent();
		} else {
			String id = context.getExternalContext().getRequestParameterMap()
					.get("id");
			Post post = postRepository.findById(Long.parseLong(id));
			if (post.getVideo() != null) {
				return new DefaultStreamedContent(new ByteArrayInputStream(
						post.getVideo()));

			} else {
				return new DefaultStreamedContent();
			}
		}
	}
}
